package computerPlayer;

import java.awt.Color;
import java.util.List;
import java.util.Random;

import miniMax.TicTacToeFramework;

public class AgressivePlayer extends Player {

	private final static String playerChar = "A";
	private final static String playerName = "AgressivePlayer";
	private TicTacToeFramework game;

	public AgressivePlayer(TicTacToeFramework ticTacToe, Player otherPlayer) {
		super(playerChar, playerName);
		super.setOtherPlayer(otherPlayer);
		super.setColor(Color.RED);
		this.game = ticTacToe;
	}

	public Integer call() throws Exception {
		System.out.println("Get called");
		return returnAggressive(game.possFields());
	}

	@Override
	public int makeMove() {
		return returnAggressive(game.possFields());
	}

	private int returnAggressive(List<Integer> moves) {
		if (moves.size() > 0) {
			TicTacToeFramework gameTmp = game;
			for (Integer integer : moves) {
				gameTmp.setCharWithID(integer, this.getPlayerChar(), false);
				int win = gameTmp.checkWin(integer);
				if (win == 1) {
					/* Computer gewinnt */
					gameTmp.removechar(integer);
					return integer;
				} else {
					gameTmp.removechar(integer);
				}
			}
			for (Integer integer : moves) {
				gameTmp.setCharWithID(integer, this.getPlayerChar(), false);
				List<Integer> nextMoves = gameTmp.possFields();
				for (Integer integer2 : nextMoves) {
					gameTmp.setCharWithID(integer2, super.getOtherPlayer().getPlayerChar(),
							false);
					int x = gameTmp.checkWin(integer2);
					if (x == 1) {
						/* Anderer Spieler gewinnt */

						/* Hebe eigenen Zug auf */
						gameTmp.removechar(integer);

						/* Hebe erdachten Zug des Gegners auf */
						gameTmp.removechar(integer2);

						/* Verbaue dem Gegner das Spiel */
						return integer2;
					} else {
						gameTmp.removechar(integer2);
					}
				}
				gameTmp.removechar(integer);
			}
			return returnRandom(moves);
		} else {
			return -1;
		}
	}

	private int returnRandom(List<Integer> moves) {
		Random r = new Random();
		int next = r.nextInt(moves.size());
		return moves.get(next);
	}

	@Override
	public void reset(TicTacToeFramework game) {
		this.game = game;
	}

	public void run() {
		// TODO Auto-generated method stub

	}

}
